﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GameCore;
using GameObject;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using System.IO;

namespace ResourceManager
{
    public class MapManager: EntityManager
    {
        Texture2D[] l_texture;
        public override void InitPrototype()
        {
            this._nprototype = ResourceDefine.Map_filename.Count<string>();
            this._prototype = new Map[_nprototype];

            l_texture = LoadTexture();

            for (int i = 0; i < _nprototype; i++)
            {
                _prototype[i] = new Map();
                ((Map)_prototype[i]).Init(ReadMapFromFile(ResourceDefine.Map_filename[i]),
                    l_texture, ResourceDefine.Map_cellWidth, ResourceDefine.Map_cellHeight,
                    ResourceDefine.Map_ncellWidth, ResourceDefine.Map_ncellHeight);
            }
        }
        private Texture2D[] LoadTexture()
        {
            l_texture = new Texture2D[100];

            for (int i = 100; i < 200; i++)
            {
                string name = "0";
                
                name += i.ToString();
                
                l_texture[i - 100] = GlobalDefine.Content.Load<Texture2D>(ResourceDefine.Map_foler_resource+name);
            }
            return l_texture;
        }
        private int[,] ReadMapFromFile(string filename)
        {
            int[,] A = new int[ResourceDefine.Map_ncellHeight, ResourceDefine.Map_ncellWidth];


            TextReader read = new StreamReader(filename);

            string dataFile = read.ReadToEnd();

            string[] arr = dataFile.Split('\n');

            for (int i = (arr.Length - ResourceDefine.Map_ncellHeight) / 2; i < arr.Length - (arr.Length - ResourceDefine.Map_ncellHeight) / 2; i++)
            {
                string[] arrrow = arr[i].Split(' ');
                Array.Reverse(arrrow);
                for (int j = (arrrow.Length - ResourceDefine.Map_ncellWidth) / 2; j < arrrow.Length - (arrrow.Length - ResourceDefine.Map_ncellWidth) / 2; j++)
                {
                    A[i - (arr.Length - ResourceDefine.Map_ncellHeight) / 2, j - (arrrow.Length - ResourceDefine.Map_ncellWidth) / 2] = int.Parse(arrrow[j]);
                }
            }
            read.Close();
            return A;
        }
        public override VisibleGameObject CreateObject(int id)
        {
            VisibleGameObject map = base.CreateObject(id);;
            ViewFrame.MaxSpace =new Point( ((Map)map).Width,((Map)map).Height);

            return map;
        }

    }
}
